package com.example.itemdecorationdemo.itemDecoration

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration

class `TestItemDecoration-BackTopTag`(context: Context) : ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val d = 100
        outRect.set(0, d, 0, 0)
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        //获取RecyclerView的左右位置
        val left = parent.paddingLeft
        val right = parent.width - parent.paddingRight
        Log.i(TAG, "left：$left  right: $right")


        val paint: Paint = Paint()
        //paint.style = Paint.Style.STROKE; //空心矩形框
        paint.style = Paint.Style.FILL//实心矩形框
        paint.color = Color.RED
        paint.strokeWidth = 10F

        val textPaint = Paint()
        textPaint.color = Color.BLACK
        textPaint.strokeWidth = 12F
        textPaint.textSize = 36F

        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val view = parent.getChildAt(i)
            val position = parent.getChildAdapterPosition(view)
            if (position % 2 == 0) {
                paint.color = Color.RED
            } else {
                paint.color = Color.BLUE
            }

            c.drawRect(
                view.left.toFloat(),
                view.top.toFloat() - 100,
                view.right.toFloat(),
                view.top.toFloat(),
                paint
            ) //绘制红色矩形
            c.drawText("TAG", view.left.toFloat(), view.top.toFloat() - 50, textPaint) //绘制文本
        }
    }

    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDrawOver(c, parent, state)
        //drawTop(c, parent, state)
        //drawBottom(c, parent, state)

    }

    companion object {
        private const val TAG = "TestItemDecoration"
    }
}